package core.process.pack;

import core.utils.Utils;
import core.wm.WM;
import core.rb.IB;
import core.rb.r.IR;
import core.rb.r.MR;
import gui.processor.Processor;
import gui.utils.ProgBar;
import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;

/*Author: John Archer, Contact: john.archer.jpa@gmail.com*/
public class MatchPack extends Thread{
    private ArrayList <MR> []  pOut;
    private final CountDownLatch stopLatch;
    private IB pIn;
    private WM matcher;
    private Processor gp;
    public MatchPack(Processor gp, CountDownLatch stopLatch, IB pIn, WM wordMatcher){
        this.stopLatch = stopLatch;
        this.gp = gp;
        this.pIn = pIn;
        this.matcher = wordMatcher;
        this.start();
    }

    public void run(){
        pOut = match();
        stopLatch.countDown();
    }

    public ArrayList <MR> []  getPOut(){return pOut;}

    private ArrayList <MR> [] match(){
        ArrayList <MR> [] mr = new ArrayList[pIn.getRef().getDNA().length()];
        for(int site=0; site<mr.length; site++){mr[site] = new ArrayList <MR> ();}
        IR iRead; String dna; String qual;
        MR wmr;
        if(gp!=null){
            gp.dPrg(ProgBar.START, pIn.getSize());
            for (int x = 0; x < pIn.getSize(); x++){
                iRead = pIn.getRead(x);
                dna = iRead.getDNA();
                qual = iRead.getQuals();
                wmr = matcher.doMatch(dna, qual, false, iRead.getI());
                if(wmr != null){mr[wmr.getStart()].add(wmr);}
                else{
                    dna = Utils.getMatchingStrand(Utils.getRevStr(dna));
                    qual = Utils.getRevStr(qual);
                    wmr = matcher.doMatch(dna, qual, true, iRead.getI());
                    if(wmr != null){mr[wmr.getStart()].add(wmr);}
                }
                gp.dPrg(ProgBar.UPDATE, x);
            }
            gp.dPrg(ProgBar.END, 0);
        }
        else{
            for (int x = 0; x < pIn.getSize(); x++){
                iRead = pIn.getRead(x);
                dna = iRead.getDNA();
                qual = iRead.getQuals();
                wmr = matcher.doMatch(dna, qual, false, iRead.getI());
                if(wmr != null){mr[wmr.getStart()].add(wmr);}
                else{
                    dna = Utils.getMatchingStrand(Utils.getRevStr(dna));
                    qual = Utils.getRevStr(qual);
                    wmr = matcher.doMatch(dna, qual, true, iRead.getI());
                    if(wmr != null){mr[wmr.getStart()].add(wmr);}
                }
            }
        }
        return mr;
    }
}